const lighthouse = require("lighthouse");
const fs = require("fs")

async function lighthousePerformance(url, browser){
    const { artifacts, lhr } = await lighthouse(url, {
        port: new URL(browser.wsEndpoint()).port,
        output: "json",
        throttling: {
            rttMs: 40,
            throughputKbps: 10 * 1024,
            cpusSlowdownMultiplier: 1,
            requestLatencyMs: 0,
            downloadThroughputKbps: 0,
            uploadThroughputKbps: 0
        },
        disableDeviceEmulation: true,
        onlyCategories: ["performance"]
    })
    // 执行lighthouse性能数据搜集:
    let result = {};
    result.entries = timing(lhr.timing.entries);
    result.audits = audits(lhr.audits);
    return result;
}


function timing(entries){
    let result = [];
    let length = entries.length;
    for(let i = 0; i < length; i++){
        result.push({name: entries[i].name, duration: entries[i].duration})
    }
    return result;
}

function audits(entries){
    let result = {};
    for(const key in entries){
        let cur = entries[key];
        let thisVal = {
            title: cur?.title,
            description: cur?.description,
            score: cur?.score ? cur?.score : 0,
            details: cur?.details && ({
                type: cur?.details?.type,
                items: cur?.details?.items
            })
        };
        if(cur?.details && cur?.details.type !== "filmstrip" && cur?.details.type !== "screenshot"){
            if(cur.details?.type && result[cur.details.type]){
                let value = result[cur.details.type]
                value.push(thisVal)
                result[cur.details.type] = value;
            }else{
                result[cur.details.type] = [thisVal];
            }
        }else if(!cur.details){
            if(!!result["timing"]){
                let value = result["timing"]
                value.push(thisVal)
                result["timing"] = value;
            }else{
                result["timing"] = [thisVal]
            }
        }
    }
    return result;
}

module.exports = {
    lighthousePerformance
}